package com.hohai.mall.common.framework.util;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Base64;

/**
 * @author: Zhao Rongjie
 * @create: 2019-07-02 15:58
 **/
public class CoderUtil {
    private static final String KEY_MD5 = "MD5";
    private static final String KEY_SHA = "SHA";
    private static final String KEY_MAC = "HmacMD5";
    private static final String KEY_SHA_256 = "SHA-256";

    public static String encodeBase64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static byte[] decodeBase64(String base64String) {
        return Base64.getDecoder().decode(base64String);
    }

    public static byte[] encryptMD5(byte[] bytes) throws Exception {
        MessageDigest digest = MessageDigest.getInstance(KEY_MD5);
        digest.update(bytes);
        return digest.digest();
    }

    public static byte[] encryptSHA(byte[] data) throws Exception {
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
        sha.update(data);
        return sha.digest();
    }

    public static byte[] encryptSHA256(byte[] data) throws Exception {
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA_256);
        sha.update(data);
        return sha.digest();
    }

    public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), KEY_MAC);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(data);
    }
}
